package com.benmei.weike.util;


import com.benmei.weike.common.Constants;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

/**
 * 短信发送工具类
 * 重构 by Peter on 2017-06-09
 * <p>
 * Created by lizhun on 15/12/22.
 */
public class SMSUtil {
    private static Logger logger = LoggerFactory.getLogger(SMSUtil.class);
    private static final String china_are_code = "86";

    /**
     * @param sms
     * @param content
     * @return boolean
     * @Purpose 短信发送公共类
     * @version 1.0
     * @author lizhun
     */
    public static boolean sendSms(Sms sms, String content) {
        boolean isSuccess = false;

        String area_phone = sms.getMemb_phone_area() + sms.getMemb_phone();
        // 发送国内短信(发送国内短信不加国家代码86)
        if (china_are_code.equals(sms.getMemb_phone_area())) {
            isSuccess = sendInlandSMS(sms.getMemb_phone(), content);
        }
        // 发送国际短信
        else {
            isSuccess = sendInterSMS(area_phone, content);
        }

        return isSuccess;
    }

    // 国际短信
    private static boolean sendInterSMS(String phoneNum, String content) {
        logger.info(" ---->> 发送国际短信 phone:" + phoneNum + ",content:" + content);
        HttpClient client = new HttpClient();
        boolean isSuccess = false;
        PostMethod post2 = new PostMethod(Constants.SMS253.inter_url);
        try {
            String contentType = "application/json";
            String charset = "UTF8";
            String jsonContent = "{ " +
                    "\"account\" : \"" + Constants.SMS253.inter_account + "\"," +
                    "\"password\" : \"" + Constants.SMS253.inter_password + "\"," +
                    "\"msg\" : \"" + content + "\"," +
                    "\"mobile\" : \"" + phoneNum + "\"" +
                    " }";


            RequestEntity requestEntity = new StringRequestEntity(jsonContent, contentType, charset);
            post2.setRequestEntity(requestEntity);
            int result = client.executeMethod(post2);
            logger.info("调用国际短信接口,HTTP STATUS:" + result);
            if (result == HttpStatus.SC_OK) {
                String resp = post2.getResponseBodyAsString();
                logger.info("国际短信接口返回消息体：" + resp);
                InterResponse interResponse = JsonUtil.toObject(resp, InterResponse.class);
                if (InterResponse.CODE.SUCCESS.equals(interResponse.getCode())) {
                    isSuccess = true;
                }
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            post2.releaseConnection();
        }
        return isSuccess;
    }

    // 国内短信
    private static boolean sendInlandSMS(String phoneNum, String content) {
        HttpClient client = new HttpClient();
        boolean isSuccess = false;
        logger.info("发送国内短信 phone:" + phoneNum + ",content:" + content);
        PostMethod post = new PostMethod(Constants.SMS253.url);
        NameValuePair[] data = {
                new NameValuePair("un", Constants.SMS253.account),
                new NameValuePair("pw", Constants.SMS253.password),
                new NameValuePair("phone", phoneNum),
                new NameValuePair("msg", content),
                new NameValuePair("rd", "1")
        };

        // 解决中文内容乱码的问题
        post.getParams().setContentCharset("UTF-8");
        post.setRequestBody(data);

        try {
            //result 是http status
            int result = client.executeMethod(post);
            logger.info("调用国内短信接口,HTTP STATUS:" + result);
            if (result == HttpStatus.SC_OK) {
                String resp = post.getResponseBodyAsString();
                logger.info("调用国内短信接口,responseBody:" + resp);
                String respCode = (resp.substring(resp.indexOf(",") + 1, resp.indexOf(",") + 2));
                if (respCode.equals("0")) {
                    isSuccess = true;
                }
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            post.releaseConnection();
        }
        return isSuccess;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        Sms sms = new Sms();
        sms.setMemb_phone("4073863948");
        sms.setMemb_phone_area("1");
        int code = (int) (Math.random() * 10000);
        try {
            sendSms(sms, "【外教君】验证码:" + code + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class InterResponse {
    public static class CODE {
        public static final String SUCCESS = "0";//提交成功

        public static final String ACCOUNT_DONT_EXISTS = "101";   //账号不存在

        public static final String PASSWORD_ERROR = "102";        //密码错误

        public static final String OVER_LENGTH = "106";           //短信内容长度错误(>536)

        public static final String FORMAT_ERROR = "108";          //手机号码格式错误(>20或<5)

        public static final String BALANCE_ERROR = "110";         //余额不足

        public static final String CONF_ERROR = "112";            //产品配置错误

        public static final String IP_ERROR = "114";              //请求ip和绑定ip不一致

        public static final String NO_INLAND_AUTH = "115";        //没有开通国内短信权限

        public static final String REQUIRED = "123";              //短信内容不能为空

        public static final String ACCOUNT_LENGTH_ERROR = "128";  //账号长度错误(>50或<=0)
    }

    private String code;
    private String msgid;
    private String error;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsgid() {
        return msgid;
    }

    public void setMsgid(String msgid) {
        this.msgid = msgid;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }
}